using System;
using System.Collections.Generic;
using System.Text;
using CodePlex.Resourceful;
using CodePlex.SpaceBlock.FS;
using CodePlex.Resourceful.Amazon.S3;
using CodePlex.SpaceBlock.UI.Test;
using CodePlex.SpaceBlock.UI.Controls;
using System.Windows.Forms;
using CodePlex.Resourceful.Microsoft.SSDS;
using CodePlex.Resourceful.Microsoft.Azure;
using CodePlex.Resourceful.Sun.CloudStorage;

namespace CodePlex.SpaceBlock.UI
{
    public class FileSystemManager
    {

        private readonly ReadOnlyList<FileSystemInfo> _fileSystemInfos;
        private ReadOnlyList<IFileSystem> _fileSystems;

        public FileSystemManager(IEnumerable<FileSystemInfo> infos)
        {

            try {
                _fileSystemInfos=  new ReadOnlyList<FileSystemInfo>(infos);

                _fileSystems = _fileSystemInfos.ConvertAll<IFileSystem>(this.ToFileSystem);

                // FOR DEBUGGING
                if (false)
                {
                    List<IFileSystem> list = new List<IFileSystem>(_fileSystems);
                    list.Clear();
                   
                    // add test fs's...
                    //string[] acct = Environment.GetEnvironmentVariable("AZURESTORAGE").Split(':');
                    //string accountName = acct[0];
                    //string primaryAccessKey = acct[1];
                    //string secondaryAccessKey = acct[2];
                    ////AzureBlobStorageClient client = new AzureBlobStorageClient(accountName, primaryAccessKey);
                    //AzureBlobStorageClient client = new AzureBlobStorageClient(
                    //  AzureConstants.DevelopmentStorageAccountName,
                    //  AzureConstants.DevelopmentStorageAccountKey,
                    //  AzureConstants.DevelopmentStorageServiceHost,
                    //  true,
                    //  false);
                    //AzureBlobStorageConnection cn = new AzureBlobStorageConnection(client);
                    //list.Add(new AzureBlobStorageFileSystem(cn));
                    string acct = Environment.GetEnvironmentVariable("SUNSTORAGE");
                    string accessKeyID = acct.Split(':')[0];
                    string secretAccessKey = acct.Split(':')[1];
                    SunCloudStorageClient client = new SunCloudStorageClient(accessKeyID, secretAccessKey);
                    SunCloudStorageConnection cn = new SunCloudStorageConnection(client);
                    SunCloudFileSystem fs = new SunCloudFileSystem(cn);
                    list.Add(fs);


                    list.Add(new LocalFileSystem());

                    _fileSystems = new ReadOnlyList<IFileSystem>(list);
                }

       
            }
            catch
            {

            }
           
        }


        public void Validate(ProgressControl pc)
        {

            List<IFileSystem> disable = new List<IFileSystem>();

            int i = 0;
            pc.SetProgress(i, _fileSystems.Count);
            foreach (IFileSystem fs in _fileSystems)
            {
                i++;

             
                pc.SetProgressText("Validating file systems... ({0} of {1})", i, _fileSystems.Count);

                try
                {
                    string c = fs.Caption;
                    pc.SetProgress(i, _fileSystems.Count);

                }
                catch (Exception ex)
                {
                    Exception newEx = CodePlexException.Format(ex, "Unable to validate file system {0} of {1}, it will be disabled for this session.\r\nError was: {2}", i, _fileSystems.Count, ex.Message);
                    UIManager.Instance.ExceptionForm.Show(newEx);
                    disable.Add(fs);
                }
            }

            if (disable.Count > 0) 
            {
                _fileSystems = _fileSystems.FindAll(delegate(IFileSystem item)
                {
                   return !disable.Contains(item);
                });
            }
           
            pc.SetProgressText("Done");

                     
        }

        public bool IsValid
        {
            get
            {
                return _fileSystems != null;
            }
        }

        public ReadOnlyList<IFileSystem> FileSystems
        {
            get
            {
                return _fileSystems;
            }
        }

        public ReadOnlyList<FileSystemInfo> FileSystemInfos
        {
            get
            {
                return _fileSystemInfos;
            }
        }


        public IFileSystem ToFileSystem(FileSystemInfo info)
        {
            if (info.Type == "Local")
            {
                return new LocalFileSystem();
            }
            if (info.Type == "S3")
            {
                string accessKeyID = info.PublicSettings.GetIfExists(UIConstants.S3Settings.AWSAccessKeyID);
                string secretAccessKey = info.PrivateSettings.GetIfExists(UIConstants.S3Settings.AWSSecretAccessKey);
                string useSSL = info.PublicSettings.GetIfExists(UIConstants.S3Settings.UseSSL);
                string defaultTransferACL = info.PublicSettings.GetIfExists(UIConstants.S3Settings.DefaultTransferACL);

                string serviceHost = info.PublicSettings.GetIfExists(UIConstants.S3Settings.ServiceHost) ?? "";
                serviceHost = serviceHost.Trim().ToLower();

                S3Connection cn;

                if (serviceHost == string.Empty || serviceHost == S3Constants.Host)
                {
                    cn = new S3Connection(accessKeyID, secretAccessKey, useSSL == true.ToString(), RequestStyle.VHost);
                }
                else
                {
                    string url = string.Format("http{0}://{1}", useSSL == true.ToString() ?"s":"",serviceHost);

                    S3Client client = new S3Client(accessKeyID, secretAccessKey, new Uri(url), delegate
                    {
                        return null;
                    });

                    cn = new S3Connection(client, RequestStyle.Path);
                }
                return new S3FileSystem(cn,S3DefaultTransferACL.Parse(defaultTransferACL));
            }
            if (info.Type == "SunCloud")
            {
                string accessKeyID = info.PublicSettings.GetIfExists(UIConstants.SunCloudSettings.AccessKeyID);
                string secretAccessKey = info.PrivateSettings.GetIfExists(UIConstants.SunCloudSettings.SecretAccessKey);
                string useSSL = info.PublicSettings.GetIfExists(UIConstants.SunCloudSettings.UseSSL);

                string serviceHost = info.PublicSettings.GetIfExists(UIConstants.SunCloudSettings.ServiceHost) ?? "";
                serviceHost = serviceHost.Trim().ToLower();

                S3Connection cn;

                if (serviceHost == string.Empty || serviceHost == SunCloudConstants.Host)
                {

                    SunCloudStorageClient client = new SunCloudStorageClient(accessKeyID, secretAccessKey, useSSL == true.ToString());
                    cn = new SunCloudStorageConnection(client);
                }
                else
                {
                    string url = string.Format("http{0}://{1}", useSSL == true.ToString() ? "s" : "", serviceHost);

                    SunCloudStorageClient client = new SunCloudStorageClient(accessKeyID, secretAccessKey, new Uri(url), delegate
                    {
                        return null;
                    });

                    cn = new SunCloudStorageConnection(client);
                }
                return new SunCloudFileSystem(cn);
            }
            if (info.Type == "Nirvanix")
            {
                string appKey = info.PublicSettings.GetIfExists(UIConstants.NirvanixSettings.AppKey);
                string appName = info.PublicSettings.GetIfExists(UIConstants.NirvanixSettings.AppName);
                string username = info.PublicSettings.GetIfExists(UIConstants.NirvanixSettings.Username);
                string password = info.PrivateSettings.GetIfExists(UIConstants.NirvanixSettings.Password);
                string useSSL = info.PublicSettings.GetIfExists(UIConstants.NirvanixSettings.UseSSL);

                return new NirvanixFileSystem(appKey,appName, username, password, useSSL == true.ToString());
            }
            if (info.Type == "SSDS")
            {
                string username = info.PublicSettings.GetIfExists(UIConstants.SSDSSettings.Username);
                string password = info.PrivateSettings.GetIfExists(UIConstants.SSDSSettings.Password);
                string useSSL = info.PublicSettings.GetIfExists(UIConstants.SSDSSettings.UseSSL);
                string authority = info.PublicSettings.GetIfExists(UIConstants.SSDSSettings.Authority);

                return new SSDSFileSystem(new SSDSConnection(username, password, useSSL == true.ToString()), authority);
            }
            if (info.Type == "Azure")
            {
                string accountName = info.PublicSettings.GetIfExists(UIConstants.AzureBlobStorageSettings.AccountName);
                string accessKey = info.PrivateSettings.GetIfExists(UIConstants.AzureBlobStorageSettings.AccessKey);
                string useSSL = info.PublicSettings.GetIfExists(UIConstants.AzureBlobStorageSettings.UseSSL);
                string serviceHost = info.PublicSettings.GetIfExists(UIConstants.AzureBlobStorageSettings.ServiceHost);

                bool usePathStyle = serviceHost == AzureConstants.DevelopmentStorageServiceHost;
                
                AzureBlobStorageClient client = new AzureBlobStorageClient(accountName, accessKey, 
                    serviceHost, usePathStyle, useSSL == true.ToString());
                
                AzureBlobStorageConnection cn = new AzureBlobStorageConnection(client);

                return new AzureBlobStorageFileSystem(cn);
            }

            throw CodePlexException.Format(Properties.Messages.Exceptions_UnknownFileSystem, info.Type);

        }

    }
}
